import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// /// 验证结果类
// class ValidationResult {
//   final bool isValid;
//   final String? errorMessage;
//
//   const ValidationResult({required this.isValid, this.errorMessage});
//
//   static const ValidationResult valid = ValidationResult(isValid: true);
//
//   static ValidationResult invalid(String message) =>
//       ValidationResult(isValid: false, errorMessage: message);
// }

/// 验证规则函数类型
// typedef ValidationRule = ValidationResult Function(String value);

class CommonTextField extends StatefulWidget {
  /// 文本控制器
  final TextEditingController textEditingController;

  /// 占位符文本
  final String? hintText;

  /// 左侧组件
  final Widget? leftWidget;

  /// 右侧组件（自定义）
  final Widget? rightWidget;

  /// 输入类型
  final TextInputType? keyboardType;

  /// 输入格式限制
  final List<TextInputFormatter>? inputFormatters;

  /// 键盘动作
  final TextInputAction? textInputAction;

  /// 是否启用
  final bool enabled;

  /// 提交回调
  final ValueChanged<String>? onSubmitted;

  /// 文本变化回调
  final ValueChanged<String>? onChanged;

  /// 最大长度
  final int? maxLength;

  /// 是否密码输入框
  final bool isPassword;

  /// 是否自动获取焦点
  final bool autofocus;

  /// 焦点节点（可选，如果不提供会自动创建）
  final FocusNode? focusNode;

  final Color? backgroundColor;

  final Color? borderColor;

  // final BorderSide? borderSide;
  final BoxBorder? border;
  final TextAlign textAlign;
  final TextStyle? style;

  const CommonTextField({
    super.key,
    required this.textEditingController,
    this.hintText,
    this.leftWidget,
    this.rightWidget,
    this.keyboardType,
    this.inputFormatters,
    this.textInputAction,
    this.enabled = true,
    this.onSubmitted,
    this.onChanged,
    this.maxLength,
    this.isPassword = false,
    this.autofocus = false,
    this.focusNode,
    this.backgroundColor,
    this.borderColor,
    this.border,
    this.textAlign = TextAlign.start,
    this.style,
  });

  @override
  State<CommonTextField> createState() => _CommonTextFieldState();
}

class _CommonTextFieldState extends State<CommonTextField> {
  bool _obscureText = true;
  late FocusNode _focusNode;
  bool _hasFocus = false;

  @override
  void initState() {
    super.initState();
    _obscureText = widget.isPassword;

    // 初始化焦点节点
    _focusNode = widget.focusNode ?? FocusNode();
    _focusNode.addListener(_onFocusChange);
  }

  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChange);
    // 只有在我们自己创建的焦点节点时才释放它
    if (widget.focusNode == null) {
      _focusNode.dispose();
    }
    super.dispose();
  }

  void _onFocusChange() {
    setState(() {
      _hasFocus = _focusNode.hasFocus;
    });
  }

  void _togglePasswordVisibility() {
    setState(() {
      _obscureText = !_obscureText;
    });
  }

  // Border(
  // bottom:
  // )
  @override
  Widget build(BuildContext context) {
    return Container(
      // height: 52.w,
      constraints: BoxConstraints(minHeight: 52.w),
      decoration: BoxDecoration(
        color: widget.backgroundColor ?? AppColor.navBgColor,
        // color: Colors.red,
        borderRadius: BorderRadius.circular(12.w),
        border: _hasFocus
            ? Border.all(
                color: _hasFocus
                    ? AppColor.primary
                    : (widget.borderColor ??
                        AppColor.textPrimary.withOpacity(0.05)),
                width: 1.w,
              )
            : widget.border ??
                Border.all(
                  color: (widget.borderColor ??
                      AppColor.textPrimary.withOpacity(0.05)),
                  width: 1.w,
                ),
      ),
      padding: EdgeInsets.symmetric(
        horizontal: 16.w,
      ),
      child: Row(children: [
        // 左侧组件
        if (widget.leftWidget != null) ...[
          widget.leftWidget!,
          SizedBox(width: 16.w),
        ],

        // 输入框
        Expanded(
          child: TextField(
            controller: widget.textEditingController,
            focusNode: _focusNode,
            obscureText: widget.isPassword ? _obscureText : false,
            autofocus: widget.autofocus,
            enabled: widget.enabled,
            keyboardType: widget.keyboardType,
            textInputAction: widget.textInputAction,
            inputFormatters: widget.inputFormatters,
            maxLength: widget.maxLength,
            textAlign: widget.textAlign,
            onChanged: widget.onChanged,
            onSubmitted: widget.onSubmitted,
            textAlignVertical: TextAlignVertical.center,
            // 文本垂直居中
            // cursorColor: widget.cursorColor ?? AppColor.primary,
            style: widget.style ??
                TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: AppColor.textPrimary.withOpacity(0.94),
                ),
            decoration: InputDecoration(
              border: InputBorder.none,
              // filled: true, // 启用填充
              // fillColor: Colors.grey[200], // 背景颜色
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
              disabledBorder: InputBorder.none,
              errorBorder: InputBorder.none,
              focusedErrorBorder: InputBorder.none,
              counterText: '',
              hintText: widget.hintText,
              isDense: true,
              isCollapsed: true,

              // 紧凑布局，有助于垂直对齐
              hintStyle: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                color: AppColor.textPrimary.withOpacity(0.5),
              ),
              contentPadding: EdgeInsets.only(bottom: 12.w, top: 12.w), // 调整内边距
            ),
          ),
        ),
        if (widget.isPassword) ...[
          SizedBox(width: 16.w),
          GestureDetector(
            onTap: _togglePasswordVisibility,
            child: AutoImage(
              _obscureText ? Assets.loginVisibleClose : Assets.loginVisibleOpen,
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
        if (widget.rightWidget != null) ...[
          SizedBox(width: 16.w),
          widget.rightWidget!,
        ],
      ]),
    );
  }
}
